use std::fmt::{Display, Formatter};

use serde::{Serialize, Serializer};

use crate::runtime::response::{Code, MagicBoxResponse};

#[derive(Debug, Clone)]
pub struct MagicBoxError {
    pub code: Code,
    pub message: String,
}

impl MagicBoxError {
    pub fn new(code: Code, message: &str) -> MagicBoxError {
        MagicBoxError { code, message: String::from(message) }
    }
}

impl Display for MagicBoxError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "code: {}, message: {}", self.code as i32, self.message)
    }
}

impl std::error::Error for MagicBoxError {}

impl Serialize for MagicBoxError {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
        serializer.serialize_some(MagicBoxResponse::<()>::new_error(self.code.clone(), self.message.clone()).as_ref())
    }
}